package com.lagou.edu.filter;

import com.lagou.edu.vo.ClientIpVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 定义全局过滤器，会对所有路由生效
 */
@Slf4j
@Component
public class ValidateFilter implements GlobalFilter, Ordered {
    Map<String,ClientIpVo> ipMap = new ConcurrentHashMap<>();
    @Value("${myip.times}")
    private String times;
    @Value("${myip.counts}")
    private String maxCount;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进来了");
        System.out.println(times + "--" + maxCount);
        // 思路：获取客户端ip，判断是否在黑名单中，在的话就拒绝访问，不在的话就放行
        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 从request对象中获取客户端ip
        String clientIp = request.getRemoteAddress().getHostString();
        if(ipMap.get(clientIp) != null){
            ClientIpVo ipVo = ipMap.get(clientIp);
            Integer thisCount = ipVo.getCount() + 1;
            long thisTime = System.currentTimeMillis() - ipVo.getStartTime();
            if (thisTime <= Integer.parseInt(times)){
                if(ipVo.getCount() >= Integer.parseInt(maxCount)){
                    String data = "请不要暴刷哈!";
                    DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }else {
                    ipVo.setCount(thisCount);
                    ipMap.put(clientIp,ipVo);
                }
            }else{
                ipVo.setCount(1);
                ipVo.setStartTime(System.currentTimeMillis());
                ipMap.put(clientIp,ipVo);
            }
        }else {
            ClientIpVo ipVo = new ClientIpVo();
            ipVo.setIp(clientIp);
            ipVo.setCount(1);
            ipVo.setStartTime(System.currentTimeMillis());
            ipMap.put(clientIp,ipVo);
        }
        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }


    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
